/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package sigl.model;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import sigl.utils.JAML;

/**
 *
 * @author uxmal
 */
public class Model {

    HashMap modules;
    HashMap packages;
    // HashMap stats;
    String filename;

    public Model() {
        modules = new HashMap();
        packages = new HashMap();
        // stats    = new HashMap();
        filename = "testdata/default_model.yml";
    }

    public Model(String filename) {

        this.filename = filename;
        File yaml = null;

        // ouverture et creation si necessaire
        try {
            yaml = new File(filename);
            // on charge le YAML si le fichier existe (on creer un fichier vide sinon)
            if (yaml.createNewFile()) {
                modules = new HashMap();
                packages = new HashMap();
                save();
            } else {
                HashMap data = (HashMap) JAML.load(yaml);
                //HashMap data = (HashMap)YAML.load(new FileReader(filename));
                if (data.containsKey("modules")) {
                    modules = (HashMap) data.get("modules");
                } else {
                    modules = new HashMap();
                }
                if (data.containsKey("packages")) {
                    packages = (HashMap) data.get("packages");
                // if (data.containsKey("stats"))    stats    = (HashMap) data.get("stats");
                } else {
                    packages = new HashMap();
                }
            }

        } catch (IOException e) {
        }

    }

    public void save() {
        saveAs(filename);
    }

    public void saveAs(String filename) {
        this.filename = filename;

        /* SOLUTION POUR VIRER LE ArrayList : 
        Set fruitsSet = new ArrayList(fruitsList);
         * (initialise un ArrayList avec un arraylist, 
         * type par defaut des listes YAML).
         */

        PrintWriter writer = null;
        try {
            writer = new PrintWriter(new BufferedWriter(new FileWriter(filename)));
        } catch (java.io.IOException exc) {
            System.out.println("Erreur lors du dump.");
        }
        writer.println("---");

        if (packages.isEmpty()) {
            writer.println("packages: {}");
        } else {
            writer.println("packages:");
        // itérateur  
        }
        Set<Map.Entry<String, HashMap>> set = packages.entrySet();

        // sauvegarde des packages
        for (Map.Entry<String, HashMap> entry : set) {

            HashMap packageData = entry.getValue();
            // on récupère les modules
            writer.println("  \"" + (String) entry.getKey() + "\":");
            if (packageData.containsKey("pass")) {
                String tmp = "" + packageData.get("pass") + "";
                if (tmp.equalsIgnoreCase("")) {
                    tmp = "0";
                }
                writer.println("    pass: \"" + tmp + "\"");
            }
             // si il ne contient pas pass, on ne l'écrit pas
            //(comme ca l'argo sait qu'il doit parser le package...)
            if (packageData.containsKey("fail")) {
                String tmp = "" + packageData.get("fail") + "";
                if (tmp.equalsIgnoreCase("")) {
                    tmp = "0";
                }
                writer.println("    fail: " + tmp);
            }
            // si il ne contient pas fail, on ne l'écrit pas
            //(comme ca l'argo sait qu'il doit parser le package...)
            if (packageData.containsKey("modules")) {
                ArrayList packageModules = (ArrayList) packageData.get("modules");


                Iterator modit = packageModules.iterator();
                if (packageModules.isEmpty()) {
                   writer.println("    modules: []");
                } else {
                    writer.println("    modules:");
                    while (modit.hasNext()) {
                        writer.println("      - \"" + (String) modit.next() + "\"");
                    }
                }
            }
        }

        // sauvegarde des modules


        if (modules.isEmpty()) {
            writer.println("modules: {}");
        } else {
            writer.println("modules:");
        // itérateur  
        }
        // itérateur  
        set = modules.entrySet();

        // NODES
        for (Map.Entry entry : set) {
            String name = String.valueOf(entry.getKey()); // convertir n'importe quoi en string
            //String name = (String) ;
            // System.out.println(name);

            writer.println("  \"" + name + "\":");
            HashMap moduleData = (HashMap) entry.getValue();            //int nodeDependencyCount = 10;

            ArrayList tmp = new ArrayList();
            if (moduleData.containsKey("dependencies")) {
                tmp = (ArrayList) moduleData.get("dependencies");
            }
            if (tmp.isEmpty()) {
               
               writer.println("    dependencies: []");
            } else {
                writer.println("    dependencies:");

                Iterator it = tmp.iterator();
                while (it.hasNext()) {
                    // on recupere le nom du package de la dependance
                    writer.println("      - \"" + it.next() + "\"");
                }
            }


            tmp = new ArrayList();
            if (moduleData.containsKey("usedBy")) {
                tmp = (ArrayList) moduleData.get("usedBy");
            }
            if (tmp.isEmpty()) {
                writer.println("    usedBy: []");
            } else {
                writer.println("    usedBy:");

                Iterator it = tmp.iterator();
                while (it.hasNext()) {
                    // on recupere le nom du package de la dependance
                    writer.println("      - \"" + it.next() + "\"");
                }
            }
        }
        writer.close();
    }

    public void setModules(HashMap modules) {
        this.modules = modules;
    }

    public void addModules(HashMap modules) {
        this.modules.putAll(modules);
    }

    public HashMap getModules() {
        return modules;
    }

    public HashMap getPackages() {
        return packages;
    }

    public void setPackages(HashMap packages) {
        this.packages = packages;
    }

    public void addPackages(HashMap packages) {
        this.packages.putAll(packages);
    }

    public int getModuleSize() {
        return modules.size();
    }

    public int getPackageSize() {
        return packages.size();
    }
}